<?php
/**
 * Description of AdminLoginComponent
 * @author Animus Inc.
 */

// Restrict Unrestricted Access
defined("_dispatch") or	die("Access Denied !");

// Constants
define('DOMROOT', dirname(dirname(__FILE__)));
        
require_once DOMROOT.'/classes/abstract/Component.php';

class AdminLoginComponent extends Component{
    
    private $_model_view;
    private $_request;
    private $_response;
    
    public function service() {
        
        // Local Variable Declaration
        $attributes = array();
        $flag = false;
        $submit_flag = null;
        $param_array = array();
        $_user_info_array = array();
        $_user_info = null;
        $_default_view = $this -> _model_view -> getDefaultView();
        $_model = $this -> _model_view -> getModel();
        $_session = $this -> _request -> getSession();
        
        // Instance of login form
        $form = $_default_view -> getLoginForm();
        $method = $form -> getMethod();
        
        // Decide which param array to pass to the form
        switch($method){
         case("post"||"POST"): $submit_flag = $form -> handleSubmit($_POST);
          break;
         case("get"||"GET"): $submit_flag = $form -> handleSubmit($_GET);
          break;
        }
        
        // Check if the form was validated
        if($submit_flag) $flag = $form -> validate();
        
        // If validation flag is empty, the form is being served 1st time
        if(!$flag)
            {
                $_default_view->setLoginForm($form);
                $_session->setUserInfo(null);
                $this ->populateDefaultResponse();
                return;
            }
        else {
        // If validate flag is not false, then the form was submitted
            $attributes = $form->getAttributes();   // Extract the submitted values from form
            $_model->setDBAttributes($attributes); // Set parameters to model
            $_fetch_array = $_model -> fetch("_user_id", "_username"); // Extract user_id from db using username
            $_user_id = $_fetch_array[0]; // Get the _user_id
            
            if(isset($_user_id)){ // If the user_id exist
            $_model -> setDBAttribute("_user_id", $_user_id); // Set the user_id to model
            $_fetch_array = $_model -> fetch("_password", "_user_id"); // Derive the password from user_id
                if(strcmp($_fetch_array[0], $form -> getFieldValue("_password")) != 0){ // If passwords are not matching, redirect back to the login view
                        $form -> setCommonError("* Invalid Credentials"); // Set "* Invalid Credentials error
                        $_session->setUserInfo(null);
                        $this ->populateDefaultResponse();
                        return;

                    }
                //Username and password seem correct    
                else{
                    array_push($param_array,"_user_id","_fname","_lname","_email","_user_type"); // Mention the fields to fetch
                    $_model -> setDBAttribute("_user_id", $_user_id); // Set user_id the model to extract user information from database
                    $_fetch_array = $_model -> fetchArray($param_array, "_user_id");// Extract the value from database using model
                    foreach($_fetch_array as $key => $value){// Save extracted value to _user_info_array
                        foreach($value as $_user_info){
                            $_user_info_array[$key] = $_user_info;
                        }
                    }
                if(strcmp($_user_info_array["_user_type"], "admin") == 0){ // // Check if the user is an admin user
                    $_session -> setUserInfo($_user_info_array); // Set user information in session
                    $_model ->setViewData($_user_info_array);
                    $this ->populateSuccessResponse(); // Set the view as success view
                    return;
                    
                }
                elseif(strcmp($_user_info_array["_user_type"], "admin") != 0){ // If user is not an admin
                    $form -> setCommonError("* Not an admin user"); // Set * Not an admin user error
                    $_session->setUserInfo(null);
                    $this ->populateDefaultResponse(); // Default view
                    return; 
                }
            }   
          }
          else{
                $form -> setCommonError("* User Doesn't Exist !"); // Set * Not an admin user error
                $_session->setUserInfo(null);
                $this ->populateDefaultResponse(); // Default view
                return;
          }
         }
        return;
    }
    
    public function execute(){
        $this -> service();
        return true;
    }
    
    public function populateSuccessResponse(){
        $this -> _response -> setValid();
        $this -> _response -> setView($this -> _model_view -> getSuccessView());
        $this -> _response -> setModel($this -> _model_view -> getModel());
        $this -> _response -> setSession($this -> _request -> getSession());
        return;
    }
    
    public function populateDefaultResponse(){
        $this -> _response -> setValid();
        $this -> _response -> setView($this -> _model_view -> getDefaultView());
        $this -> _response -> setModel($this -> _model_view -> getModel());
        $this -> _response -> setSession($this -> _request -> getSession());
        return;
    }
     
    // Getters and Setters
    
    public function setModelView(ModelView $_model_view){
        $this -> _model_view = $_model_view;
        return;
    }
    
    public function getModelView(){
        $this -> _model_view;
        return;
    }
    
    
    public function setRequest(AnimusRequest $Request){
        $this -> _request = $Request;
        return;
    }
    
    public function getRequest(){
        return $this -> _request;
    }
    
    public function setResponse(AnimusResponse $Response){
        $this -> _response = $Response;
        return;
    }
    
    public function getResponse(){
        return $this ->_response;
    }
}
?>
